<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import * as admin from '@/api/admin.js'
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

// 课程列表数据
const courses = ref([]);
const updateModal = ref(false);
const addModal = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const search_title = ref('');
const search_type = ref('');
const tearch_list = ref([]);

const updateData = ref({
  id: '',
  title: '',
  description: '',
  teacherId: '',
  price: 0,
  img: '',
  duration:0
})

const addData = ref({
  title: '',
  description: '',
  teacherId: '',
  price: 0,
  duration: 0,
  img:''
})

const showDialog = (row) => {
  console.log(row.title);
  updateData.value.id = row.id;
  updateData.value.title = row.title;
  updateData.value.description = row.description;
  updateData.value.teacherId = row.teacherId;
  updateData.value.price = row.price;
  updateData.value.img = row.img;
  updateData.value.duration = row.duration;
}


// 模拟获取数据
const fetchCourses = async() => {
  const param_user = {
    role: "teacher",
    status: '正常'
  }
  const tearch_data = await admin.findtearchlist(param_user)
  tearch_list.value = tearch_data.data;

  const param = {
    currentPage: currentPage.value,
    title: search_title.value,
    type: search_type.value,
  }
  const res = await admin.findCourse(param)
  courses.value = res.data;
  total.value = res.total;
  console.log(res);
};

// 搜索课程
const searchCourse = () => {
  fetchCourses();
};

// 删除课程
const deleteCourse = (id) => {
  const param = {
    id: id
  }
  ElMessageBox.confirm('确认删除该课程？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await admin.delCourse(param)
      console.log(res);
      if (res.code == 0) {
        fetchCourses();
        ElMessage.success('删除成功');
      }
    })
    .catch();
};

// 修改课程
const editCourse = async (id) => {
  const res = await admin.updateCourse(updateData.value);
  if (res.code == 0) {
    fetchCourses();
    ElMessage.success(`修改成功`);
    updateModal.value = false;
  }
  
};

const handleSubmit = async() => {
  const res = await admin.addCourse(addData.value);
  if (res.code == 0) {
    fetchCourses();
    ElMessage.success(`添加成功`);
    addModal.value = false;
  }
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchCourses();
};

//上传成功的回调函数
const uploadSuccess = (result)=>{
    updateData.value.img = result.data;
    addData.value.img = result.data
}


// 初始化加载数据
onMounted(() => {
  fetchCourses();
});
</script>

<template>
  <div class="course-page">
    <!-- 搜索框 -->
    <el-card class="search-box">
      <el-form :inline="true">
        <el-form-item label="课程标题">
          <el-input v-model="search_title" placeholder="请输入课程标题" clearable />
        </el-form-item>
        <!-- <el-form-item label="课程类型">
          <el-input v-model="search_type" placeholder="请输入课程类型" clearable />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="searchCourse">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 添加课程按钮 -->
    <el-card class="add-box">
      <el-button type="success" @click="addModal=true">➕ 添加课程</el-button>
    </el-card>

    <!-- 课程列表 -->
    <el-card>
      <el-table :data="courses" border style="width: 100%">
        <!-- <el-table-column prop="id" label="ID" width="60" /> -->
        <el-table-column label="封面" width="120">
          <template #default="{ row }">
            <el-image :src="row.img" fit="img" style="width: 100px; height: 60px; border-radius: 6px;" />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="课程标题" />
        <el-table-column prop="description" label="课程描述" />
        <el-table-column prop="yonghu" label="授课教师" />
        <el-table-column prop="price" label="价格（¥）" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="120" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showDialog(row),updateModal=true">修改</el-button>
            <el-button type="danger" size="small" @click="deleteCourse(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="handlePageChange"
      />
    </div>

  <el-drawer
    v-model="updateModal"
    title="修改信息"
    direction="rtl"
    class="demo-drawer"
    >
    <div class="demo-drawer__content">
    <el-form 
        ref="updateFormRef" 
        :model="updateData" 
        :rules="rules" 
        label-width="80px"
        >
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="updateData.title" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="updateData.description" 
            type="textarea" 
            placeholder="请输入课程描述"
          />
        </el-form-item>
        <el-form-item label="教师ID" prop="teacherId">
          <!-- <el-input v-model="updateData.teacherId" placeholder="请输入教师ID" /> -->
          <el-select v-model="updateData.teacherId" placeholder="请选择教师">
            <el-option v-for="teacher in tearch_list" :key="teacher.username" :label="teacher.username" :value="teacher.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="updateData.price" :min="0" />
        </el-form-item>

        <el-form-item label="时长(分钟)" prop="duration">
          <el-input-number v-model="updateData.duration" :min="1" />
        </el-form-item>

        <el-form-item label="课程封面" prop="img">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/upload/image"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess"
          >
            <img v-if="updateData.img" :src="updateData.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="editCourse">提交</el-button>
      </div>
    </div>
  </el-drawer>

<el-dialog 
  v-model="addModal" 
  title="添加课程" 
  width="40%" 
  center 
  class="custom-dialog"
>
  <el-form 
    ref="addFormRef"
    :model="addData" 
    :rules="rules"
    label-width="100px" 
    style="padding: 10px 20px"  
    size="large"
  >
    <el-form-item label="课程名称" prop="title">
      <el-input v-model="addData.title" placeholder="请输入课程名称" clearable />
    </el-form-item>

    <el-form-item label="课程描述" prop="description">
      <el-input 
        v-model="addData.description" 
        type="textarea"
        placeholder="请输入课程描述"
        maxlength="200"
        show-word-limit
        clearable
      />
    </el-form-item>

    <el-form-item label="讲师 ID" prop="teacherId">
      <!-- <el-input v-model="addData.teacherId" placeholder="请输入讲师 ID" clearable /> -->
      <el-select v-model="addData.teacherId" placeholder="请选择教师">
            <el-option v-for="teacher in tearch_list" :key="teacher.username" :label="teacher.username" :value="teacher.id" />
          </el-select>
    </el-form-item>

    <el-form-item label="价格 (¥)" prop="price">
      <el-input-number 
        v-model="addData.price" 
        :min="0" 
        :precision="2"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="课程时长 (分钟)" prop="duration">
      <el-input-number 
        v-model="addData.duration" 
        :min="1" 
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="封面图片" prop="img">
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/upload/image"
        name="file"
        :show-file-list="false"
        :on-success="uploadSuccess"
        >
        <img v-if="addData.img" :src="addData.img" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
  </el-form>

  <template #footer>
    <span class="dialog-footer">
      <el-button @click="addModal = false">取消</el-button>
      <el-button 
        type="primary"
        @click="handleSubmit"
      >
        提交
      </el-button>
    </span>
  </template>
</el-dialog>

  </div>
</template>

<style>
.course-page {
  padding: 20px;
  background: #f7f8fa;
}

.search-box {
  margin-bottom: 15px;
}

.add-box {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}



.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
